package inject

import (
	"context"
	"gfast/app/basic/dao"
	"gfast/app/basic/model"
	"github.com/gogf/gf/frame/g"
	"strconv"
	"strings"
	"time"
)

// GenCode 生成编码
func GenCode(ctx context.Context, key string) (code string, err error) {
	tx, _ := g.DB().Ctx(ctx).Begin()
	m := tx.Model(dao.CodeRule.Table)
	defer func() {
		if !tx.IsClosed() {
			_ = tx.Rollback()
		}
	}()

	rule := &model.CodeRule{}
	err = m.Where(dao.CodeRule.Columns.Key, key).Scan(&rule)
	if err != nil || rule.Id == 0 {
		rule = &model.CodeRule{
			Key:           key,
			Name:          "",
			Prefix:        "",
			Time:          "",
			SerialBegin:   1,
			SerialLength:  4,
			SerialCounter: 0,
		}
		var id int64
		id, err = m.InsertAndGetId(rule)
		if err != nil {
			return
		}
		rule.Id = int(id)
	}
	rule.SerialCounter++
	_, err = m.Where(dao.CodeRule.Columns.Id, rule.Id).Update(g.Map{
		dao.CodeRule.Columns.SerialCounter: rule.SerialCounter,
	})
	if err != nil {
		return
	}
	err = tx.Commit()
	if err != nil {
		return
	}

	seq := strconv.Itoa(rule.SerialCounter)
	if len(seq) < rule.SerialLength {
		seq = strings.Repeat("0", rule.SerialLength-len(seq)) + seq
	}
	return rule.Prefix + time.Now().Format("060102") + seq, nil
}
